<?php

namespace App\Jobs;

use App\Enums\RefundState;
use App\Models\Refund;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;

class OrderRefund extends BaseJob
{
    public string $queue = 'payment';

    public function __construct(protected Refund $refund)
    {
    }

    /**
     * @throws InvalidArgumentException
     * @throws InvalidConfigException
     */
    public function handle(): void
    {
        $this->refund->state = RefundState::PROCESS;
        $this->refund->save();

        $payment = $this->refund->order->payment->init();

        $response = $payment->getClient()
            ->postJson('v3/refund/domestic/refunds', [
                'out_trade_no' => '',
                'out_refund_no' => $this->refund->no,
                'reason' => '全额退款',
                'notify_url' => '', // 通知url必须为外网可访问的url，不能携带参数
                'amount' => [
                    'refund' => 0,
                    'total' => 0,
                    'currency' => 'CNY',
                ],
            ]);

        $response->toArray();

        QueryRefund::dispatch($this->refund);
    }
}
